package cn.edu.scau.cmi.ema.service;

import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;


import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.persistence.Query;
import java.util.Iterator;
@Service("FiletypeService")
@Transactional

public class FiletypeServiceImpl extends CmiEmaService implements FiletypeService {
	public FiletypeServiceImpl() {
	}

	@Transactional
	public Filetype saveFiletype(Filetype filetype) {
		Set<Crawlerfile> existingCrawlerfilesForFiletype = new HashSet<Crawlerfile>();

		Set<Crawlerfile> selectedCrawlerfilesForFiletype = filetype.getCrawlerfilesForFiletype();

		if (filetype.getId() == null) {

			Filetype existingFiletype = filetypeDAO.findFiletypeByPhysicalPrimaryKey(filetype.getName());

			if (isEquals(filetype, existingFiletype)) {
				return existingFiletype;
			}

			filetype = filetypeDAO.store(filetype);
			filetypeDAO.flush();

			for (Crawlerfile relatedCrawlerfile : selectedCrawlerfilesForFiletype) {
				relatedCrawlerfile.setFiletype(filetype);
				crawlerfileDAO.store(relatedCrawlerfile);
			}
		} else {
			Filetype existingFiletype = filetypeDAO.findFiletypeByPrimaryKey(filetype.getId());

			existingCrawlerfilesForFiletype = existingFiletype.getCrawlerfilesForFiletype();

			Set<Crawlerfile> prepareDeleteCrawlerfilesForFiletype = new HashSet<Crawlerfile>();
			Set<Crawlerfile> prepareAddCrawlerfilesForFiletype = new HashSet<Crawlerfile>();

			prepareDeleteCrawlerfilesForFiletype.addAll(selectedCrawlerfilesForFiletype);
			prepareDeleteCrawlerfilesForFiletype.addAll(existingCrawlerfilesForFiletype);

			prepareAddCrawlerfilesForFiletype.addAll(selectedCrawlerfilesForFiletype);
			prepareAddCrawlerfilesForFiletype.addAll(existingCrawlerfilesForFiletype);

			prepareDeleteCrawlerfilesForFiletype.removeAll(selectedCrawlerfilesForFiletype);
			prepareAddCrawlerfilesForFiletype.removeAll(existingCrawlerfilesForFiletype);

			for (Crawlerfile relatedCrawlerfile : prepareAddCrawlerfilesForFiletype) {
				relatedCrawlerfile.setFiletype(filetype);
				crawlerfileDAO.store(relatedCrawlerfile);
			}

			for (Crawlerfile relatedCrawlerfile : prepareDeleteCrawlerfilesForFiletype) {
				relatedCrawlerfile.setFiletype(null);
				crawlerfileDAO.store(relatedCrawlerfile);
			}
			filetype = filetypeDAO.store(filetype);
			filetypeDAO.flush();
		}

		crawlerfileDAO.flush();
		return filetype;
	}

	public void deleteFiletype(Filetype filetype) {
		filetypeDAO.remove(filetype);
		filetypeDAO.flush();
	}

	@Transactional
	public void deleteFiletypes(Set<Integer> deleteFiletypesId) {
		Query query = filetypeDAO.createNamedQuery("deleteFiletypesById", -1, -1);
		query.setParameter(1, deleteFiletypesId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Filetype> loadFiletypes() {
		return filetypeDAO.findAllFiletypes();

	}

	@Transactional
	public Set<Filetype> loadReferenceFiletypes(Set<Filetype> filetypes) {
		Iterator<Filetype> filetypesIterator = filetypes.iterator();
		Set<Filetype> referencedFiletypes = new HashSet<>();
		while (filetypesIterator.hasNext()) {
			Filetype currentFiletype = filetypesIterator.next();

			if (!currentFiletype.getCrawlerfilesForFiletype().isEmpty()) {
				referencedFiletypes.add(currentFiletype);
				continue;
			}
		}
		return referencedFiletypes;
	}

	public Set<Filetype> loadFiletypesByIdSet(Set<Integer> filetypeIdSet) {

		Iterator<Integer> filetypeIdIterator = filetypeIdSet.iterator();
		Set<Filetype> filetypeSet = new HashSet<>();
		while (filetypeIdIterator.hasNext()) {
			Integer id = filetypeIdIterator.next();
			Filetype currentFiletype = filetypeDAO.findFiletypeById(id);
			filetypeSet.add(currentFiletype);
		}
		return filetypeSet;
	}

	@Transactional
	public List<Filetype> findAllFiletypes(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Filetype>(filetypeDAO.findAllFiletypes(startResult, maxRows));
	}

	@Transactional
	public Filetype findFiletypeByPrimaryKey(Integer id) {
		return filetypeDAO.findFiletypeByPrimaryKey(id);
	}

	@Transactional
	public Integer countFiletypes() {
		return ((Long) filetypeDAO.createQuerySingleResult("select count(o) from Filetype o").getSingleResult())
				.intValue();
	}

	@Transactional
	public Integer countFiletypes(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Filetype.class);
		return ((Long) filetypeDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 * 
	 */
	@Transactional
	public Integer countFiletypesByName(String queryName) {
		Query query = filetypeDAO.createNamedQuery("countFiletypesByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countFiletypesByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Filetype.class);
		Session session = entityManager.unwrap(Session.class);
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadFiletypeObjectReferencedSet(Filetype filetype) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();

		Set<Integer> crawlerfilesIds = new HashSet<Integer>();
		for (Crawlerfile obj : filetype.getCrawlerfilesForFiletype()) {

			crawlerfilesIds.add(obj.getId());
		}
		objectReferencedSetMap.put("crawlerfilesIds", crawlerfilesIds);

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadFiletypeClassReferencedSet(Filetype filetype) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("crawlerfiles", crawlerfileDAO.findAllCrawlerfiles());

		return classReferencedSetMap;
	}

	public boolean isEquals(Filetype filetype, Object obj) {
		if (obj == filetype)
			return true;
		if (!(obj instanceof Filetype))
			return false;
		Filetype comparedFiletype = (Filetype) obj;
		if (!CheckPropertyEqual(filetype.getName(), comparedFiletype.getName())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

